package userAPI

import (
	"github.com/gin-gonic/gin"
	"go-gin-init/app/models/req"
	"go-gin-init/app/service"
	"go-gin-init/common/result"
	"go-gin-init/common/tool"
	"go-gin-init/common/xerr"
)

// UserRegister
// @Summary 用户注册
// @Description
// @Tags USER
// @Accept json
// @Produce json
// @Param Param body req.UserRegisterReq true "请求参数"
// @Success 200 {object} result.JsonResult "{"code":200,"data":{},"msg":"SUCCESS"}"
// @Failure 400 {object} result.JsonResult "{"code":200,"data":{},"msg":""}"
// @Failure 500 {string} string "Internal Server Error"
// @Router /user/register [post]
func UserRegister(c *gin.Context) {
	var u req.UserRegisterReq
	err := c.ShouldBind(&u)
	if err != nil {
		result.ParamErrorResult(c, err)
		return
	}

	usermodel := service.NewDefaultUserModel()

	otherUser, err := usermodel.FindByUserName(u.UserName)
	if err != nil && err != service.ErrNotFound {
		result.JsonRsp(c, nil, err)
		return
	}

	if otherUser != nil {
		result.JsonRsp(c, nil, xerr.NewErrMsg("账户已存在"))
		return
	}

	userMap := tool.StructToMap(u)
	err = usermodel.CreateUser(userMap)
	if err != nil {
		result.JsonRsp(c, nil, xerr.NewErrCode(xerr.SERVER_COMMON_ERROR))
	}
	result.JsonRsp(c, nil, nil)
}
